package com.system.questionnairesurvey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.questionnairesurvey.common.util.response.R;
import com.system.questionnairesurvey.entity.mybatis.ProjectEntity;
import com.system.questionnairesurvey.mapper.ProjectMapper;
import com.system.questionnairesurvey.service.ProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 项目表 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2022-09-16
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, ProjectEntity> implements ProjectService {

    @Override
    public R listProject(String key, Integer num, Integer size) {
        PageHelper.startPage(num, size);
        List<ProjectEntity> entities = listProjectByKeyword(key);
        return R.buildSuccess(new PageInfo<>(entities));
    }

    /**
     * 查询项目信息
     */
    private List<ProjectEntity> listProjectByKeyword(String key) {
        LambdaQueryWrapper<ProjectEntity> wrapper = Wrappers.<ProjectEntity>lambdaQuery().like(ProjectEntity::getName, key);
        return this.list(wrapper);
    }

    @Override
    public R saveProject(ProjectEntity entity) {
        if (exist(entity)) {
            return R.buildFail("项目名已存在");
        }
        return R.buildSuccess(this.save(entity));
    }

    /**
     * 项目是否存在
     */
    private boolean exist(ProjectEntity entity) {
        LambdaQueryWrapper<ProjectEntity> wrapper = Wrappers.<ProjectEntity>lambdaQuery()
                .ne(Objects.nonNull(entity.getId()), ProjectEntity::getId, entity.getId())
                .eq(ProjectEntity::getName, entity.getName());
        return this.getOne(wrapper) != null;
    }

    @Override
    public R updateProject(ProjectEntity entity) {
        if (exist(entity)) {
            return R.buildFail("项目名已存在");
        }
        return R.buildSuccess(this.updateById(entity));
    }
}
